package org.jeecg.modules.operations.assistant.xcbd.controller;

import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.system.query.QueryRuleEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.operations.assistant.xcbd.entity.YearCountInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import java.util.HashMap;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.operations.assistant.xcbd.entity.XcbdCollectionRecord;
import org.jeecg.modules.operations.assistant.xcbd.entity.XcbdWorkflow;
import org.jeecg.modules.operations.assistant.xcbd.entity.XcbdSalesContract;
import org.jeecg.modules.operations.assistant.xcbd.service.IXcbdSalesContractService;
import org.jeecg.modules.operations.assistant.xcbd.service.IXcbdCollectionRecordService;
import org.jeecg.modules.operations.assistant.xcbd.service.IXcbdWorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.shiro.authz.annotation.RequiresPermissions;
 /**
 * @Description: 销售合同
 * @Author: jeecg-boot
 * @Date:   2024-12-21
 * @Version: V1.0
 */
@Api(tags="销售合同")
@RestController
@RequestMapping("/xcbd/xcbdSalesContract")
@Slf4j
public class XcbdSalesContractController extends JeecgController<XcbdSalesContract, IXcbdSalesContractService> {

	@Autowired
	private IXcbdSalesContractService xcbdSalesContractService;

	@Autowired
	private IXcbdCollectionRecordService xcbdCollectionRecordService;

	@Autowired
	private IXcbdWorkflowService xcbdWorkflowService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param xcbdSalesContract
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "销售合同-分页列表查询")
	@ApiOperation(value="销售合同-分页列表查询", notes="销售合同-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<XcbdSalesContract>> queryPageList(XcbdSalesContract xcbdSalesContract,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("contractStatus", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<XcbdSalesContract> queryWrapper = QueryGenerator.initQueryWrapper(xcbdSalesContract, req.getParameterMap(),customeRuleMap);
		Page<XcbdSalesContract> page = new Page<XcbdSalesContract>(pageNo, pageSize);
		IPage<XcbdSalesContract> pageList = xcbdSalesContractService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param xcbdSalesContract
     * @return
     */
    @AutoLog(value = "销售合同-添加")
    @ApiOperation(value="销售合同-添加", notes="销售合同-添加")
    @RequiresPermissions("xcbd:xcbd_sales_contract:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody XcbdSalesContract xcbdSalesContract) {
        xcbdSalesContractService.saveSalesContract(xcbdSalesContract);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param xcbdSalesContract
     * @return
     */
    @AutoLog(value = "销售合同-编辑")
    @ApiOperation(value="销售合同-编辑", notes="销售合同-编辑")
    @RequiresPermissions("xcbd:xcbd_sales_contract:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody XcbdSalesContract xcbdSalesContract) {
        xcbdSalesContractService.updateById(xcbdSalesContract);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "销售合同-通过id删除")
    @ApiOperation(value="销售合同-通过id删除", notes="销售合同-通过id删除")
    @RequiresPermissions("xcbd:xcbd_sales_contract:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        xcbdSalesContractService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "销售合同-批量删除")
    @ApiOperation(value="销售合同-批量删除", notes="销售合同-批量删除")
    @RequiresPermissions("xcbd:xcbd_sales_contract:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.xcbdSalesContractService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequiresPermissions("xcbd:xcbd_sales_contract:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XcbdSalesContract xcbdSalesContract) {
        return super.exportXls(request, xcbdSalesContract, XcbdSalesContract.class, "销售合同");
    }

    /**
     * 导入
     * @return
     */
    @RequiresPermissions("xcbd:xcbd_sales_contract:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, XcbdSalesContract.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-收款记录-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "收款记录-通过主表ID查询")
	@ApiOperation(value="收款记录-通过主表ID查询", notes="收款记录-通过主表ID查询")
	@GetMapping(value = "/listXcbdCollectionRecordByMainId")
    public Result<IPage<XcbdCollectionRecord>> listXcbdCollectionRecordByMainId(XcbdCollectionRecord xcbdCollectionRecord,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<XcbdCollectionRecord> queryWrapper = QueryGenerator.initQueryWrapper(xcbdCollectionRecord, req.getParameterMap());
        Page<XcbdCollectionRecord> page = new Page<XcbdCollectionRecord>(pageNo, pageSize);
        IPage<XcbdCollectionRecord> pageList = xcbdCollectionRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param xcbdCollectionRecord
	 * @return
	 */
	@AutoLog(value = "收款记录-添加")
	@ApiOperation(value="收款记录-添加", notes="收款记录-添加")
	@PostMapping(value = "/addXcbdCollectionRecord")
	public Result<String> addXcbdCollectionRecord(@RequestBody XcbdCollectionRecord xcbdCollectionRecord) {
		xcbdCollectionRecordService.saveCollectionRecord(xcbdCollectionRecord);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param xcbdCollectionRecord
	 * @return
	 */
	@AutoLog(value = "收款记录-编辑")
	@ApiOperation(value="收款记录-编辑", notes="收款记录-编辑")
	@RequestMapping(value = "/editXcbdCollectionRecord", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editXcbdCollectionRecord(@RequestBody XcbdCollectionRecord xcbdCollectionRecord) {
		xcbdCollectionRecordService.updateById(xcbdCollectionRecord);
		return Result.OK("编辑成功!");
	}

	 /**
	  * 更新到账状态
	  * @param xcbdCollectionRecord
	  * @return
	  */
	 @AutoLog(value = "更新到账状态")
	 @ApiOperation(value="更新到账状态", notes="更新到账状态")
	 @RequiresPermissions("collectionRecord:updateReceiptStatus")
	 @RequestMapping(value = "/updateReceiptStatus", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> updateReceiptStatus(@RequestBody XcbdCollectionRecord xcbdCollectionRecord) {
		 xcbdCollectionRecordService.updateReceiptStatus(xcbdCollectionRecord);
		 return Result.OK("编辑成功!");
	 }

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "收款记录-通过id删除")
	@ApiOperation(value="收款记录-通过id删除", notes="收款记录-通过id删除")
	@DeleteMapping(value = "/deleteXcbdCollectionRecord")
	public Result<String> deleteXcbdCollectionRecord(@RequestParam(name="id",required=true) String id) {
		xcbdCollectionRecordService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "收款记录-批量删除")
	@ApiOperation(value="收款记录-批量删除", notes="收款记录-批量删除")
	@DeleteMapping(value = "/deleteBatchXcbdCollectionRecord")
	public Result<String> deleteBatchXcbdCollectionRecord(@RequestParam(name="ids",required=true) String ids) {
	    this.xcbdCollectionRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXcbdCollectionRecord")
    public ModelAndView exportXcbdCollectionRecord(HttpServletRequest request, XcbdCollectionRecord xcbdCollectionRecord) {
		 // Step.1 组装查询条件
		 QueryWrapper<XcbdCollectionRecord> queryWrapper = QueryGenerator.initQueryWrapper(xcbdCollectionRecord, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<XcbdCollectionRecord> pageList = xcbdCollectionRecordService.list(queryWrapper);
		 List<XcbdCollectionRecord> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "收款记录");
		 mv.addObject(NormalExcelConstants.CLASS, XcbdCollectionRecord.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("收款记录报表", "导出人:" + sysUser.getRealname(), "收款记录"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importXcbdCollectionRecord/{mainId}")
    public Result<?> importXcbdCollectionRecord(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<XcbdCollectionRecord> list = ExcelImportUtil.importExcel(file.getInputStream(), XcbdCollectionRecord.class, params);
				 for (XcbdCollectionRecord temp : list) {
                    temp.setSalesContractId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 xcbdCollectionRecordService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-收款记录-end----------------------------------------------*/

    /*--------------------------------子表处理-工作流程-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "工作流程-通过主表ID查询")
	@ApiOperation(value="工作流程-通过主表ID查询", notes="工作流程-通过主表ID查询")
	@GetMapping(value = "/listXcbdWorkflowByMainId")
    public Result<IPage<XcbdWorkflow>> listXcbdWorkflowByMainId(XcbdWorkflow xcbdWorkflow,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<XcbdWorkflow> queryWrapper = QueryGenerator.initQueryWrapper(xcbdWorkflow, req.getParameterMap());
        Page<XcbdWorkflow> page = new Page<XcbdWorkflow>(pageNo, pageSize);
        IPage<XcbdWorkflow> pageList = xcbdWorkflowService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param xcbdWorkflow
	 * @return
	 */
	@AutoLog(value = "工作流程-添加")
	@ApiOperation(value="工作流程-添加", notes="工作流程-添加")
	@PostMapping(value = "/addXcbdWorkflow")
	public Result<String> addXcbdWorkflow(@RequestBody XcbdWorkflow xcbdWorkflow) {
		xcbdWorkflowService.save(xcbdWorkflow);
		return Result.OK("添加成功！");
	}

	 /**
	  * 副总经理审批
	  * @param xcbdWorkflow
	  * @return
	  */
	 @AutoLog(value = "工作流程-添加")
	 @ApiOperation(value="工作流程-添加", notes="工作流程-添加")
	 @RequiresPermissions("xcbd:viceGeneralManager")
	 @PostMapping(value = "/viceGeneralManager")
	 public Result<String> viceGeneralManager(@RequestBody XcbdWorkflow xcbdWorkflow) {
		 xcbdWorkflowService.approval(xcbdWorkflow,xcbdWorkflow.getStep());
		 return Result.OK("副总经理审批审批成功！");
	 }

	 /**
	  * 总经理审批
	  * @param xcbdWorkflow
	  * @return
	  */
	 @AutoLog(value = "工作流程-添加")
	 @ApiOperation(value="工作流程-添加", notes="工作流程-添加")
	 @RequiresPermissions("xcbd:generalManager")
	 @PostMapping(value = "/generalManager")
	 public Result<String> generalManager(@RequestBody XcbdWorkflow xcbdWorkflow) {
		 xcbdWorkflowService.approval(xcbdWorkflow,xcbdWorkflow.getStep());
		 return Result.OK("总经理审批审批成功！");
	 }

    /**
	 * 编辑
	 * @param xcbdWorkflow
	 * @return
	 */
	@AutoLog(value = "工作流程-编辑")
	@ApiOperation(value="工作流程-编辑", notes="工作流程-编辑")
	@RequestMapping(value = "/editXcbdWorkflow", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editXcbdWorkflow(@RequestBody XcbdWorkflow xcbdWorkflow) {
		xcbdWorkflowService.updateById(xcbdWorkflow);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工作流程-通过id删除")
	@ApiOperation(value="工作流程-通过id删除", notes="工作流程-通过id删除")
	@DeleteMapping(value = "/deleteXcbdWorkflow")
	public Result<String> deleteXcbdWorkflow(@RequestParam(name="id",required=true) String id) {
		xcbdWorkflowService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "工作流程-批量删除")
	@ApiOperation(value="工作流程-批量删除", notes="工作流程-批量删除")
	@DeleteMapping(value = "/deleteBatchXcbdWorkflow")
	public Result<String> deleteBatchXcbdWorkflow(@RequestParam(name="ids",required=true) String ids) {
	    this.xcbdWorkflowService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXcbdWorkflow")
    public ModelAndView exportXcbdWorkflow(HttpServletRequest request, XcbdWorkflow xcbdWorkflow) {
		 // Step.1 组装查询条件
		 QueryWrapper<XcbdWorkflow> queryWrapper = QueryGenerator.initQueryWrapper(xcbdWorkflow, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<XcbdWorkflow> pageList = xcbdWorkflowService.list(queryWrapper);
		 List<XcbdWorkflow> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "工作流程");
		 mv.addObject(NormalExcelConstants.CLASS, XcbdWorkflow.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工作流程报表", "导出人:" + sysUser.getRealname(), "工作流程"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importXcbdWorkflow/{mainId}")
    public Result<?> importXcbdWorkflow(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<XcbdWorkflow> list = ExcelImportUtil.importExcel(file.getInputStream(), XcbdWorkflow.class, params);
				 for (XcbdWorkflow temp : list) {
                    temp.setWorkOrderId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 xcbdWorkflowService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-工作流程-end----------------------------------------------*/

	 /**
	  * 测试报表数据
	  */
	 @GetMapping(value = "/report/getYearCountInfo")
	 public Result<List<YearCountInfo>> getYearCountInfo() {
		 return Result.ok(xcbdSalesContractService.getYearCountInfo());
	 }
	 @GetMapping(value = "/report/getMonthCountInfo")
	 public Result<List<YearCountInfo>> getMonthCountInfo() {
		 return Result.ok(xcbdSalesContractService.getMonthCountInfo());
	 }
	 @GetMapping(value = "/report/getWeekCountInfo")
	 public Result<List<YearCountInfo>> getWeekCountInfo() {
		 return Result.ok(xcbdSalesContractService.getWeekCountInfo());
	 }

	 @GetMapping(value = "/collectionRecord/getYearCountInfo")
	 public Result<List<YearCountInfo>> getCollectionRecordYearCountInfo() {
		 return Result.ok(xcbdCollectionRecordService.getYearCountInfo());
	 }
	 @GetMapping(value = "/collectionRecord/getMonthCountInfo")
	 public Result<List<YearCountInfo>> getCollectionRecordMonthCountInfo() {
		 return Result.ok(xcbdCollectionRecordService.getMonthCountInfo());
	 }
	 @GetMapping(value = "/collectionRecord/getWeekCountInfo")
	 public Result<List<YearCountInfo>> getCollectionRecordWeekCountInfo() {
		 return Result.ok(xcbdCollectionRecordService.getWeekCountInfo());
	 }
}
